import util from './util_method.js'
import http from './http.js'
const appMethod = {
    //文本提示
    info: function (msg, cb) {
        wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            complete: function () {
                typeof cb == "function" && cb();
            }
        });
    },
    //成功提示
    success: function (msg, cb) {
        wx.showToast({
            title: msg,
            icon: 'success',
            image: '/images/ok.png',
            duration: 2000,
            complete: function () {
                typeof cb == "function" && cb();
            }
        });
    },
    //错误提示
    error: function (msg, cb) {
        wx.showToast({
            title: msg,
            image: '/images/error.png',
            duration: 2000,
            complete: function () {
                typeof cb == "function" && cb();
            }
        });
    },
    //警告提示
    warning: function (msg, cb) {
        wx.showToast({
            title: msg,
            image: '/images/warning.png',
            duration: 2000,
            complete: function () {
                typeof cb == "function" && cb();
            }
        });
    },

    saveUser(user) {
        if (!util.isObject(user)) {
            this.error('用户信息错误');
        }
        try {
            wx.setStorageSync('userinfo', JSON.stringify(user));
        } catch (e) {
            this.error('保存用户信息失败');
        }
    },
    getUser() {
        try {
          let userinfo = wx.getStorageSync('userinfo')
          if (!!userinfo) {
            userinfo = JSON.parse(userinfo);
          } else {
            userinfo = {};
          }
          return userinfo;
        } catch (e) {
            this.error('获取用户信息失败');
        }
    },
    getUserToken: function () {
        var userinfo = this.getUser();
        if (userinfo && typeof userinfo == 'object' && userinfo.token) {
            // 还要检查token是否过期
            let date = new Date();
            var now = date.getTime() / 1000;
            if (now >= (userinfo.expiretime - 20)) {
                return false;
            }

            return userinfo.token;
        }

        return false;
    },
    //构造CDN地址
    cdnurl: function (url) {
        return url.toString().match(/^https?:\/\/(.*)/i) ? url : http.host + url;
    },
    processImg(list, field = 'image') {
        let that = this;
        if (util.isArray(list)) {
            list.forEach(function (item, i) {
                if (util.isObject(item)) {
                    //值为对象
                    if (!util.isUndefined(item[field])) {
                        item[field] = that.cdnurl(item[field]);
                    }
                } else {
                    //值为字符串
                    if (util.isString(item)) {
                        list[i] = that.cdnurl(item)
                    }
                }
            })

        } else if (util.isObject(list)) {
            if (!util.isUndefined(list[field])) {
                list[field] = that.cdnurl(list[field]);
            }
        } else {
            //字符串
            if (util.isString(item)) {
                list = that.cdnurl(list);
            }
        }

        return list;
    },
  //显示登录或授权提示
  showLoginModal: function (cb) {
    var that = this;
    wx.showModal({
      title: '温馨提示',
      content: '当前无法获取到你的个人信息，无法正常登陆，请重新授权',
      showCancel: false,
      success: function (res) {
        cb && cb();
      }
    });
  },

  //判断是否登录
  checkLogin: function (cb) {
    var that = this;
    if (this.getUserToken()) {
      typeof cb == "function" && cb(that.getUser());
    } else {
      //未登录跳转到登陆页面
      wx.redirectTo({
        url: '/pages/login/authorize'
      });
    }
  },

  //搜索历史
  saveSearch(keyword, key) {
    if (!!keyword) {
      let data = this.getSearch(key);
      if (data.indexOf(keyword) <= -1) {
        data.unshift(keyword);
        if (data.length > 8) {
          data.pop();
        }
        wx.setStorageSync(key, JSON.stringify(data));
      }
    }
   
  },
  saveCache(data, key, cache= 2*24*3600) {
    let date = new Date();
    let curtime = date.getTime()/1000;
    let config = {
      time : curtime,
      cache : cache,
      data : data
    }
     
    wx.setStorageSync(key, JSON.stringify(config));
  },
  getCache(key) {
    let data = wx.getStorageSync(key);
    if (!!data) {
      data = JSON.parse(data);
      let date = new Date();
      let curtime = date.getTime() / 1000;
      let remin = curtime - data.time
      
      if(remin > data.cache && data.cache != 0) {
        return null;
      }

      return data.data;
    } else {
      return null;
    }
    return data; 
  },
  getSearch(key) { 
    let data = wx.getStorageSync(key);
    if (!!data) {
      data = JSON.parse(data);
    } else {
      return [];
    }
    console.log(data);
    return data; 
  }
}
module.exports = appMethod;

